﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <script type="text/javascript">
        var Node = function (name) {
            this.children = [];
            this.name = name;
        };

        Node.prototype = {
            add: function (childNode) {
                this.children.push(childNode);
            },
            remove: function (childNode) {
                for (var i = 0, len = this.children.length; i < len; i++) {
                    if (this.children[i] === childNode) {
                        this.children.splice(i, 1);
                        return;
                    }
                }
            },
            getChildren: function (i) {
                return this.children[i];
            },
            hasChildren: function(){
                return this.children.length > 0;
            }
        };
        var str = "";
        function traverse(indent, node) {
            str += Array(indent++).join("--") + node.name + "\n";
            for (var i = 0, len = node.children.length; i < len; i++) {
                //traverse(indent++, node.children[i]);
                arguments.callee.apply(this, [indent, node.children[i]]);
            }
            return str;
        }

        function run() {
            var tree = new Node("root");
            var left = new Node("left")
            var right = new Node("right");
            var leftleft = new Node("leftleft");
            var leftright = new Node("leftright");
            var rightleft = new Node("rightleft");
            var rightright = new Node("rightright");

            tree.add(left);
            tree.add(right);
            tree.remove(right);  // note: remove
            tree.add(right);
            left.add(leftleft);
            left.add(leftright);
            right.add(rightleft);
            right.add(rightright);

            alert(traverse(1, tree));
        }

        run();
    </script>
</body>
</html>
